package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.modular.system.entity.BtyWx;
import cn.stylefeng.guns.sys.modular.system.entity.Emp;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.mapper.DeptEmpMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.EmpMapper;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.guns.sys.modular.system.model.params.EmpParam;
import cn.stylefeng.guns.sys.modular.system.model.result.WxmsgPushResult;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * emp管理
 * </p>
 *
 * @author liuy
 * @since
 */
@Service
public class EmpService extends ServiceImpl<EmpMapper, Emp> {

    @Resource
    private DeptEmpMapper deptEmpMapper;
    @Resource
    private UserService userService;

    @Resource
    private BtyWxService btyWxService;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    /**
     * emp管理
     * @author fengshuonan
     * @Date 2018/12/23 6:05 PM
     */
    public Page<Map<String, Object>> list(EmpParam emp) {
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.list(page, emp);
    }

    /**
     * 根据员工生成用户信息
     * @param type
     * @param empIds
     * @param deptId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseData generateUserFromEmp(String type, String empIds, Long deptId) {
        List<Integer> empids=new ArrayList<>();
        if("emp".equals(type)){//根据员工生成
            if(ToolUtil.isEmpty(empIds)){
                return ResponseData.error("缺少必要参数");
            }
            String[] empIdAry = empIds.split(",");
            for(String id:empIdAry){
                empids.add(Integer.valueOf(id));
            }
        }else if ("dept".equals(type)){//根据部门生成
            if(ToolUtil.isEmpty(deptId)){
                return ResponseData.error("缺少必要参数");
            }
            //获取部门下的员工id集合
            empids = deptEmpMapper.listEmpsByDept(deptId);
        }else{
            return ResponseData.error("参数不合法");
        }
        //id获取员工信息
        List<Emp> emps = listEmps(empids);
        Map<Integer, Emp> empMap = emps.stream().collect(Collectors.toMap(Emp::getId, Function.identity()));

        // 遍历集合组装user数据
        List<UserDto> userList=new ArrayList<>();
        for(Integer empid : empids){
            Emp emp = empMap.get(empid);
            if(emp.getTel()==null || emp.getTel().equals("")){
                continue;
            }
            List<User> userByphone = userService.getUserByphone(emp.getTel());
            if(userByphone.size()>0){
                continue;//若存在该用户，则不生成
            }
            UserDto u=new UserDto();
            u.setAccount(emp.getTel());
            String pwd=emp.getTel().substring(emp.getTel().length()-6);
            u.setPassword(pwd);
            u.setName(emp.getXm());
//            u.setSex();
            u.setPhone(emp.getTel());
            u.setRoleId("1356795608519041025");
            u.setDeptId(deptId);

            userList.add(u);
        }
        for(UserDto dto :userList){
            userService.addUser(dto);
        }
        return ResponseData.success(userList.size());
        
    }

    public List<Emp> listEmps(List<Integer> empIds){
        List<Emp> result = Lists.newArrayList();
        List<List<Integer>> lists = Lists.partition(empIds, 2000);
        for(List<Integer> item:lists){
            List<Emp> emps = baseMapper.listEmps(item);
            result.addAll(emps);
        }
        return result;
    }

    public List<Emp> listParam(EmpParam param) {
        QueryWrapper<Emp> q=new QueryWrapper<>();
        if(ToolUtil.isNotEmpty(param.getTel())){
            q.eq("tel",param.getTel());
        }
        List<Emp> emps = baseMapper.selectList(q);
        return emps;
    }

    @Async
    public ResponseData shengriTuisong() {
        StringBuffer msg = new StringBuffer();
        Date curDate =new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
        SimpleDateFormat sdf_l = new SimpleDateFormat("yyyy年MM月dd日");
        String curDate_str = sdf.format(curDate);
        QueryWrapper<Emp> q=new QueryWrapper<>();
        q.eq("SUBSTRING(sfz, 11, 4)",curDate_str);
        q.apply("LEN(sfz)=18");
        q.apply("status ='YGZT02'");
        List<Emp> emps = baseMapper.selectList(q);

        if(!emps.isEmpty()){
            Map<Integer,String> fenzuMap =new HashMap<Integer,String>();
            Integer zu = 1;
            for(int i=0;i<emps.size();i++){
                Emp e = emps.get(i);
                String list = fenzuMap.get(zu);
                if(list==null){
                    list = e.getXm();
                }else {
                    list+=","+e.getXm();
                }
                fenzuMap.put(zu,list);
                if(list.length()>197){
                    zu++;
                }
            }

            QueryWrapper<BtyWx> q1 = new QueryWrapper<>();
            List<BtyWx> list=btyWxService.list(q1);
            List<String> openIds = new ArrayList<String>();
            for (int i = 0; i < list.size(); i++) {
                String openid=list.get(i).getOpenid();
                openIds.add(openid);
            }

            JSONArray list_tmp = new JSONArray();
            for(int i=1;i<=zu;i=i+2){
                String first = "今天全公司共"+emps.size()+"人一起过生日,公司全体同事恭祝大家生日快乐、岁岁平安、合家欢乐！";
                String f3 = fenzuMap.get(i);
                String remark = fenzuMap.get(i+1);
                String q_xinxi = "生日提醒";
                String q_riqi = sdf_l.format(curDate);
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(first,remark,q_xinxi,q_riqi,f3);
                list_tmp.add(tempObj);
            }

            //发送生日祝福
            weChatSendTempMsgService.sendMsgUpdateContentByTempQuery(openIds.toArray(new String[openIds.size()]), null, list_tmp);

        }else {
            msg.append("日期["+sdf_l.format(curDate)+"]生日人数是0");
        }
        return ResponseData.success(msg.toString());
    }
}
